package com.hjs.homework.word_count;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class WordCountJava {
    public static void main(String[] args) throws Exception {
        String inputPath = "D:\\Homework\\hello.txt";
        String outputPath = "D:\\Homework\\output";

        //获取运行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //读取数据
        DataSet<String> dataSet = env.readTextFile(inputPath);

        //处理数据
        FlatMapOperator<String, Tuple2<String, Integer>> maped = dataSet.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(new Tuple2<String, Integer>(word, 1));
                }
            }
        });

        UnsortedGrouping<Tuple2<String, Integer>> grouped = maped.groupBy(0);

        AggregateOperator<Tuple2<String, Integer>> sumed = grouped.sum(1);

        //输出结果
        sumed.writeAsCsv(outputPath,"\n","\t" ).setParallelism(1);

        //启动执行
        env.execute();
    }
}
